package com.itpan.Controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.itpan.Entity.Employee;
import com.itpan.Entity.PurchaseOrder;
import com.itpan.Entity.PurchaseOrderDetail;
import com.itpan.Service.EmployeeService;
import com.itpan.Service.PurchaseOrderDetailService;
import com.itpan.Service.PurchaseOrderService;
import com.itpan.Utils.EntityValidate;
import com.itpan.Utils.PurchaseOrderExcelListener;
import com.itpan.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 修改：2024/6/19进行修改：逻辑优化和cache优化
 */

@Api(value = "采购总表接口")
@RestController
@RequestMapping("/purchaseorder")
public class PurchaseOrderController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    @Autowired
    private EntityValidate entityValidate;

    @Cacheable(value = "purchaseorder",key = "'all'")
    @ApiOperation(value = "查询全部采购主表")
  @GetMapping("/all")
    public R<List<PurchaseOrder>> getall(){
        List<PurchaseOrder> list= purchaseOrderService.getall();
        return R.success(list);
    }

    @Cacheable(value = "purchaseorder",key = "#p0"+'-'+"#p1")
    @GetMapping("/allpage")
    @ApiOperation(value = "查询全部采购明细带分页")
    public R<List<PurchaseOrder>> getallpage(Integer page,Integer pageSize){
        List<PurchaseOrder> list = purchaseOrderService.getallpage(page, pageSize);
        return R.success(list);
    }

    @GetMapping("/getalltable")
    @ApiOperation(value = "查询全部带表格")
    public void getalltable(HttpServletResponse response) throws IOException {
        List<PurchaseOrder> list = purchaseOrderService.getall();
        setExcelRespProp(response,"采购主表");
        EasyExcel.write(response.getOutputStream(), PurchaseOrder.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("采购主表列表")
                .doWrite(list);
        response.getOutputStream().flush();
    }



    @PostMapping("/getbymutil")
    @ApiOperation(value = "模糊查询不带表格")
    public R<List<PurchaseOrder>> getbymutil(@RequestBody PurchaseOrder purchaseOrder){
        List<PurchaseOrder> list = purchaseOrderService.getByMutil(purchaseOrder);
        return R.success(list);
    }


    /**
     *模糊查询带表格
     */
    @PostMapping("/getbymutiltable")
    @ApiOperation(value = "模糊查询带表格")
    public void getbymutiltable(@RequestBody PurchaseOrder purchaseOrder,HttpServletResponse response) throws IOException {
        List<PurchaseOrder> list = purchaseOrderService.getByMutil(purchaseOrder);
        setExcelRespProp(response,"采购主表");
        EasyExcel.write(response.getOutputStream(), PurchaseOrder.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("采购主表列表")
                .doWrite(list);
        response.getOutputStream().flush();
    }


    @CacheEvict(value = "purchaseorder",allEntries = true)
    @PostMapping("/addone")
    @ApiOperation(value = "新增一采购主表")
    public R<String> addone(@RequestBody PurchaseOrder purchaseOrder){

        //先判断填写的员工存不存在，再进行逻辑的判断
        Employee emp = employeeService.getById(purchaseOrder.getEmployeeID());

        if(emp==null){
            return R.error("员工不存在");
        }

        if(!entityValidate.isValidateOfPurchaseOrder(purchaseOrder)){
            return R.error("信息格式错误");
        }

        //不为空则能进行添加逻辑
        purchaseOrderService.saveOne(purchaseOrder);
        return R.success("新增成功");
    }


    /*
    批量导入采购主表
     */

    @CacheEvict(value = "purchaseorder",allEntries = true)
    @PostMapping("addall")
    @ApiOperation(value = "批量导入采购主表记录")
    public R<String> addall(@RequestParam("file")MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return R.error("文件不能为空");
        }
        EasyExcel.read(file.getInputStream(), PurchaseOrder.class,new PurchaseOrderExcelListener(purchaseOrderService, employeeService, entityValidate))
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .doRead();;
        return R.success("批量导入成功");
    }





    /*
    更新采购表
     */
    @CacheEvict(value = "purchaseorder",allEntries = true)
    @PostMapping("/update")
    @ApiOperation(value = "更新采购表接口")
    public R<String> update(@RequestBody PurchaseOrder purchaseOrder){
        //更新前先判断是否存在对应的员工编号

        Employee emp = employeeService.getById(purchaseOrder.getEmployeeID());

        if(emp==null) return R.error("员工不存在");

        //如果员工存在则进行更新逻辑
        if(!entityValidate.isValidateOfPurchaseOrder(purchaseOrder)){
            return R.error("信息格式错误");
        }

        purchaseOrderService.update(purchaseOrder);
        return R.success("更新成功");
    }


    /*
    根据id删除采购表
     */
    @CacheEvict(value = "purchaseorder",allEntries = true)
    @DeleteMapping("/delete")
    @ApiOperation(value = "根据采购表id删除采购表记录")
    public R<String> deletebyId(Long id){

        //需要判断改采购主表是不是还有采购详细表所引用

        //先拿到主表
        PurchaseOrder pu = purchaseOrderService.getById(id);

        //再拿到详细表     //逻辑错：是不是可以查出很多个详细表
//        PurchaseOrderDetail pud = purchaseOrderDetailService.getById(pu.getOrderID());

        List<PurchaseOrderDetail> listofDe = purchaseOrderDetailService.getMainpurchaseByMainId(pu.getOrderID());

        if(listofDe.size()>0){
            return R.error("删除失败，还有相应的详细采购数据");
        }


        purchaseOrderService.delete(id);
        return R.success("删除成功");
    }


    @ApiOperation(value = "查询一定时间范围内的订单")
    @GetMapping("/purchaseorders")
    public R<List<PurchaseOrder>> getPurchaseOrders(@RequestParam("startDate") String startDate,
                                                    @RequestParam("endDate") String endDate) {
        LocalDateTime start = LocalDateTime.parse(startDate);
        LocalDateTime end = LocalDateTime.parse(endDate);
        List<PurchaseOrder> orders = purchaseOrderService.getOrdersWithinDateRange(start, end);
        return R.success(orders);
    }

    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // Ensure the file is not cached
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
    }


}
